<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 分红达标模板
 *
 * @icon fa fa-circle-o
 */
class BonusStands extends Backend
{

    /**
     * BonusStands模型对象
     * @var \app\common\model\BonusStands
     */
    protected $model = null;

    protected $LevModel = null;

    protected $proModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\BonusStands;
        $this->LevModel = new \app\common\model\BonusLevel;
        $this->proModel = new \app\common\model\Product;
        $this->view->assign("stateList", $this->model->getStateList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $list = [];
        $params = $this->request->param();
        $limit = $this->request->param("limit");
        $offset = $this->request->param("offset");
        $count = $this->model->count();
        if ($count) {
            $list = $this->model->limit($offset, $limit)->select();
            if ($list) {
                $lev = $this->LevModel->column("title", "id");
                foreach ($list as $key => $val) {
                    $list[$key]["lev"] = $lev[$val["lev_id"]];
                    $list[$key]["pros"] = $this->proModel->whereIn("id", $val["pro_ids"])->value("group_concat(name)");
                }
            }
        }
        $result = ['total' => $count, 'rows' => $list];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $lev_list = $this->_level_lists();
            $pro_list = $this->_pro_lists();
            $this->assign("lev_list", $lev_list);
            $this->assign("pro_list", $pro_list);
            return $this->view->fetch();
        }
        $params = $this->request->post();
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            $check = Db::name("bonus_stands")->where("lev_id = " . $params["lev_id"])->count();
            if ($check) {
                throw new \Exception("该等级已设置，无需重复！！！");
            } else {
                //是否采用模型验证
                $data["lev_id"] = $params["lev_id"];
                $data["tranAmt"] = $params["tranAmt"];
                $data["nums"] = $params["nums"];
                $data["pro_ids"] = implode(",", $params["pro_ids"]);
                $data["createTime"] = strtotime($params["createTime"]);
                $data["state"] = $params["state"];
                $result = Db::name('bonus_stands')->insert($data);
                Db::commit();
            }
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $lev_list = $this->_level_lists();
            $pro_list = $this->_pro_lists();
            $this->assign("lev_list", $lev_list);
            $this->assign("pro_list", $pro_list);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            $data["lev_id"] = $params["lev_id"];
            $data["tranAmt"] = $params["tranAmt"];
            $data["nums"] = $params["nums"];
            $data["pro_ids"] = implode(",", $params["pro_ids"]);
            $data["modifyTime"] = strtotime($params["modifyTime"]);
            $data["state"] = $params["state"];
            $result = Db::name('bonus_stands')->where("id = " . $ids)->update($data);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 分红等级
     */
    public function _level_lists()
    {
        return \app\common\model\BonusLevel::where("state = 1")->field("id,title")->select();
    }

    public function _pro_lists()
    {
        $buildSql = \app\common\model\BonusProduct::where("isStatus = 1")->field("pro_id")->buildSql();
        return \app\common\model\Product::where("id in {$buildSql}")->field("id,name")->select();
    }
}
